/*
 * Copyright 2007 Rob Nielsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.proxymatic.apps.factory.handlers;

import com.googlecode.proxymatic.apps.factory.InstanceProvider;
import com.googlecode.proxymatic.core.handlers.method.CheckingParameterModifier;

public class ResolvingFactoryParameterModifier implements CheckingParameterModifier {
    private final InstanceProvider instanceProvider;

    public ResolvingFactoryParameterModifier(InstanceProvider instanceProvider) {
        this.instanceProvider = instanceProvider;
    }

    // FIX ROB Dup between supportsParameterTypes and modifyParameters
    public boolean supportsParameterTypes(Class[] fromParameterTypes, Class[] toParameterTypes) {
        if (fromParameterTypes.length >= toParameterTypes.length) {
            return false;
        }
        int fromPos = 0;
        for (int toPos = 0; toPos < toParameterTypes.length; toPos++) {
            Class toParameterType = toParameterTypes[toPos];
            if (fromParameterTypes.length > fromPos && toParameterType.equals(fromParameterTypes[fromPos])) {
                fromPos++;
            } else if (!instanceProvider.containsInstance(toParameterType)) {
                return false;
            }
        }
        return fromPos == fromParameterTypes.length;
    }

    public Object[] modifyParameters(Object[] fromParameters, Class[] fromParameterTypes, Class[] toParameterTypes) {
        Object[] toParameters = new Object[toParameterTypes.length];
        int fromPos = 0;
        for (int toPos = 0; toPos < toParameterTypes.length; toPos++) {
            Class toParameterType = toParameterTypes[toPos];
            if (fromParameterTypes.length > fromPos && toParameterType.equals(fromParameterTypes[fromPos])) {
                toParameters[toPos] = fromParameters[fromPos++];
            } else {
                toParameters[toPos] = instanceProvider.getInstance(toParameterTypes[toPos]);
            }
        }
        return toParameters;
    }
}
